package acs.offer.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import acs.offer.client.ClientTask;
import acs.offer.collection.Params;
import acs.offer.constant.EventType;

public class AcsController implements MessageObserver {
	private static AcsController instance = new AcsController();
	private static Logger logger = LoggerFactory.getLogger(AcsController.class);

	private static final String OFFER="offer";
	
	private Map<String,ClientTask> taskMap=new HashMap<String, ClientTask>();

	public static AcsController getInstance() {
		return instance;
	}

	@Override
	public void handle(int eventType, Params param) {
		switch (eventType) {
		case EventType.START_SERVICE:
            MessageQueue.getInstance().putMessage(EventType.QUERY_CACHE,Params.build());
            break;
		case EventType.QUERY_CACHE:
			param.put("duration", 2);
			param.put("timeUnit", TimeUnit.SECONDS);
			this.loadOffer(param);
			break;
		case EventType.TIMEOUT_WHEN_GET_TARGET_OFFER:
			handleTargetOfferTimeOut(param);
			break;
		case EventType.RESPONSE_FOR_DATA:
			handleTargetOfferResponse(param);
			break;
		default: {
			logger.error("Can't handle event:{}", eventType);
			break;
		}
		}
	}
	/**
	 * 得到之前生成的ClientTask
	 * @param type
	 * @return
	 */
	private ClientTask getPreClientTask(String type) {
		return taskMap.get(type);
	}
	/**
	 * 获取或创建clientTask，在刚开始处理请求时，调用此方法
	 * @param type
	 * @return
	 */
	private ClientTask getOrGeneratorClientTask(String type) {
		ClientTask clientTask = taskMap.get(type);
		if(clientTask == null) {
			clientTask=new ClientTask();
			clientTask.setType(type);
			taskMap.put(type, clientTask);
		}
		return clientTask;
	}
	
	private void handleTargetOfferTimeOut(Params param) {
		//前面必须要有ClientTask存在
		ClientTask clientTask = this.getPreClientTask(OFFER);
		clientTask.handleTargetOfferTimeOut(param);
	}

	private void handleTargetOfferResponse(Params param) {
		ClientTask clientTask = this.getPreClientTask(OFFER);
		clientTask.handleTargetOfferResponse(param);
	}

	private void loadOffer(Params param) {
		//异步 获取offer，获取存在或产生一个新的ClientTask
        ClientTask clientTask = this.getOrGeneratorClientTask(OFFER);
        clientTask.loadCache(param);
	}

	@Override
	public void removeService(String requestType) {
		// TODO Auto-generated method stub
		
	}
}
